﻿using MediatR;
using RBAC_Class.Domain;
using RBAC_Class.ErrorCode;
using RBAC_Class.Infrastructrue.Interfaces;
using RBAC_Class.Write.API.Application.Command.Roles;

namespace RBAC_Class.Write.API.Application.CommandHandler.Roles
{
    public class AddRoleCommandHandler:IRequestHandler<AddRoleCommand,APIResult<int>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IBaseRepository<RolePermission> rolePermissionRep;
        private readonly ILogger<AddRoleCommandHandler> logger;

        public AddRoleCommandHandler(IBaseRepository<Role> roleRep, IBaseRepository<RolePermission> rolePermissionRep, ILogger<AddRoleCommandHandler> logger)
        {
            this.roleRep = roleRep;
            this.rolePermissionRep = rolePermissionRep;
            this.logger = logger;
        }

        public Task<APIResult<int>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            using (var tran = roleRep.Context.Database.BeginTransaction())
            {
                try
                {
                    #region 添加角色
                    var role = new Role
                    {
                        RoleName = request.RoleName,
                        Status = 1,
                        CreateTime = DateTime.Now,
                        IsDelete = false
                    };
                    roleRep.Add(role);
                    #endregion
                    #region 添加角色权限
                    
                    foreach (var item in request.permissionID)
                    {
                        var rolePermission = new RolePermission
                        {
                            RoleID = role.RoleID,
                            PermissionID = item,
                            CreateTime = DateTime.Now,
                            IsDelete = false
                        };
                        rolePermissionRep.Add(rolePermission);
                    };
                    #endregion
                    

                    // 提交事务
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.Message);
                    // 回滚事务
                    tran.Rollback();
                }
                return Task.FromResult(new APIResult<int>()
                {
                    Code = ResultCode.Success,
                    Message = "添加成功",
                    Data = 1
                });
            }
        }
    }
}
